﻿using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.LogManager.Data.Entity.Model.StorageManagers
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
    public static partial class LogScopeItemManager
    {
        #region Public Members

        #region DeleteItemsAsync

        static partial void OnRemove(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, Sidvall.Data.ObjectParameterCollection objectParameters, System.Collections.Generic.IEnumerable<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> items, global::Sidvall.Business.TaskContext taskContext);
        static partial void OnBeforeDeleteItems(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<int, global::Sidvall.Data.DeleteCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext);
        static partial void OnAfterDeleteItems(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<int, global::Sidvall.Data.DeleteCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task DeleteItemsAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<int, global::Sidvall.Data.DeleteCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext)
        {
            System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> dbQuery;
            
            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));
            OnBeforeDeleteItems(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
            {
                if ((dataPortalContext.OperationContext.RowStartIndex > 0) || (dataPortalContext.OperationContext.RowCount > 0))
                {
                    if (dataPortalContext.OperationContext.SortItems == null)
                        dataPortalContext.OperationContext.SortItems = new global::Sidvall.Data.SortItemCollection<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>();
                    if (dataPortalContext.OperationContext.SortItems.Count == 0)
                    {
                        dataPortalContext.OperationContext.SortItems.Add(global::Sidvall.LogManager.Data.Fields.LogScopeItemField.LogScopeItemId, Sidvall.Data.SortType.Ascending);
                    }
                }
                if (storageManager.ObjectContext.Database.Connection.State == System.Data.ConnectionState.Closed)
                    await storageManager.ObjectContext.Database.Connection.OpenAsync().ConfigureAwait(false);
                dbQuery = storageManager.ObjectContext.LogScopeItem;
                var query = (from o in dbQuery
                             select o);
                query = PrepareFilter(query, dataPortalContext.OperationContext.Filter);
                query = PrepareSort(query, dataPortalContext.OperationContext.SortItems);
                if (dataPortalContext.OperationContext.RowStartIndex > 0)
                    query = query.Skip(dataPortalContext.OperationContext.RowStartIndex.Value);
                if (dataPortalContext.OperationContext.RowCount > 0)
                    query = query.Take(dataPortalContext.OperationContext.RowCount.Value);
                var items = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectsAsync(query).ConfigureAwait(false);
                var taskContext = new global::Sidvall.Business.TaskContext();
                OnRemove(storageManager, dataPortalContext.ObjectParameters, items, taskContext);
                await taskContext.DoTaskAsync().ConfigureAwait(false);
                if (taskContext.Result == Sidvall.Business.DataPortalResult.None)
                    storageManager.ObjectContext.LogScopeItem.RemoveRange(items);
                dataPortalContext.ResultValueItem = await storageManager.ObjectContext.SaveChangesAsync().ConfigureAwait(false);
            }
            OnAfterDeleteItems(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion
        #region NewItemAsync

        static partial void OnBeforeNewItem(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.CreateCriteria> dataPortalContext);
        public static async Task NewItemAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.CreateCriteria> dataPortalContext)
        {
            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));

            OnBeforeNewItem(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
                dataPortalContext.ResultValueItem = new global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem();
        }

        #endregion
        #region NewItemsAsync

        static partial void OnBeforeNewItems(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.CreateCriteria> dataPortalContext);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task NewItemsAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.CreateCriteria> dataPortalContext)
        {
            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));

            OnBeforeNewItems(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
                dataPortalContext.ResultValueList = new global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItemCollection();
        }

        #endregion
        #region GetItemAsync

        static partial void OnBeforeGetItem(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext);
        static partial void OnAfterGetItem(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task GetItemAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext)
        {
            System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> dbQuery;

            OnBeforeGetItem(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
            {
                dbQuery = storageManager.ObjectContext.LogScopeItem.AsNoTracking();
                dbQuery = ProcessIncludedEntities(dbQuery, dataPortalContext.OperationContext.IncludedEntities);
                var query = (from o in dbQuery
                             select o);
                query = PrepareFilter(query, dataPortalContext.OperationContext.Filter);
                query = PrepareSort(query, dataPortalContext.OperationContext.SortItems);
                dataPortalContext.ResultValueItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectAsync(query, Sidvall.Data.DataRowState.Unchanged).ConfigureAwait(false);
            }
            OnAfterGetItem(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion
        #region GetItemsAsync

        static partial void OnBeforeGetItems(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchListCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext);
        static partial void OnAfterGetItems(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchListCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext);
        static partial void OnAfterPrepareFilter(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchListCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext, ref System.Linq.IQueryable<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> query);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task GetItemsAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, global::Sidvall.Data.FetchListCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField, global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation>> dataPortalContext)
        {
            System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> dbQuery;
            long? totalRowCount;

            OnBeforeGetItems(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
            {
                if ((dataPortalContext.OperationContext.RowStartIndex > 0) || (dataPortalContext.OperationContext.RowCount > 0))
                {
                    if (dataPortalContext.OperationContext.SortItems == null)
                        dataPortalContext.OperationContext.SortItems = new global::Sidvall.Data.SortItemCollection<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>();
                    if (dataPortalContext.OperationContext.SortItems.Count == 0)
                    {
                        dataPortalContext.OperationContext.SortItems.Add(global::Sidvall.LogManager.Data.Fields.LogScopeItemField.LogScopeItemId, Sidvall.Data.SortType.Ascending);
                    }
                }
                dbQuery = storageManager.ObjectContext.LogScopeItem.AsNoTracking();
                dbQuery = ProcessIncludedEntities(dbQuery, dataPortalContext.OperationContext.IncludedEntities);
                var query = (from o in dbQuery
                             select o);
                query = PrepareFilter(query, dataPortalContext.OperationContext.Filter);
                OnAfterPrepareFilter(storageManager, dataPortalContext, ref query);
                if ((dataPortalContext.OperationContext.RowStartIndex > 0) || (dataPortalContext.OperationContext.RowCount > 0))
                    totalRowCount = await query.LongCountAsync();
                else
                    totalRowCount = null;
                query = PrepareSort(query, dataPortalContext.OperationContext.SortItems);
                if (dataPortalContext.OperationContext.RowStartIndex > 0)
                    query = query.Skip(dataPortalContext.OperationContext.RowStartIndex.Value);
                if (dataPortalContext.OperationContext.RowCount > 0)
                    query = query.Take(dataPortalContext.OperationContext.RowCount.Value);
                var entityItems = new global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItemCollection();
                await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.LoadEntityObjectsAsync(query, entityItems, Sidvall.Data.DataRowState.Unchanged).ConfigureAwait(false);
                dataPortalContext.ResultValueList = entityItems;
                dataPortalContext.TotalRowCount = totalRowCount;
            }
            OnAfterGetItems(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion
        #region GetItemCountAsync

        static partial void OnBeforeGetItemCount(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<long, global::Sidvall.Data.FetchCountCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext);
        static partial void OnAfterGetItemCount(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<long, global::Sidvall.Data.FetchCountCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task GetItemCountAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<long, global::Sidvall.Data.FetchCountCriteria<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext)
        {
            System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> dbQuery;

            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));

            OnBeforeGetItemCount(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
            {
                dbQuery = storageManager.ObjectContext.LogScopeItem.AsNoTracking();
                var query = (from o in dbQuery
                             select o);
                query = PrepareFilter(query, dataPortalContext.OperationContext.Filter);
                dataPortalContext.ResultValueItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectCountAsync(query).ConfigureAwait(false);
            }
            OnAfterGetItemCount(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion
        #region SaveItemAsync

        static partial void OnBeforeSaveItem(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, Sidvall.Data.SaveContext<global::Sidvall.LogManager.Data.ILogScopeItem>> dataPortalContext);
        static partial void OnAfterSaveItem(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, Sidvall.Data.SaveContext<global::Sidvall.LogManager.Data.ILogScopeItem>> dataPortalContext);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task SaveItemAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, Sidvall.Data.SaveContext<global::Sidvall.LogManager.Data.ILogScopeItem>> dataPortalContext)
        {
            global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem;
            System.Collections.Generic.Dictionary<string, object> ids;
            
            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));
            OnBeforeSaveItem(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
            if (dataPortalContext.Result == Sidvall.Business.DataPortalResult.None)
            {
                ids = new System.Collections.Generic.Dictionary<string, object>();
                if (storageManager.ObjectContext.Database.Connection.State == System.Data.ConnectionState.Closed)
                    await storageManager.ObjectContext.Database.Connection.OpenAsync().ConfigureAwait(false);
                entityItem = await ProcessResourceObjectAsync(storageManager, ids, dataPortalContext.OperationContext.Item, dataPortalContext.OperationContext.Settings, dataPortalContext.ObjectParameters).ConfigureAwait(false);
                if (Sidvall.Data.DataRowContextManager.GetDataRowState(entityItem) == Sidvall.Data.DataRowState.Added)
                    storageManager.ObjectContext.LogScopeItem.Add(entityItem);
                await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.SaveChangesAsync(storageManager.ObjectContext).ConfigureAwait(false);
                dataPortalContext.ResultValueItem = entityItem;
                dataPortalContext.ResultValueIsNewObject = true;
            }
            OnAfterSaveItem(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion
        #region SaveItemsAsync

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task SaveItemsAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.LogManager.Data.ILogScopeItem, Sidvall.Data.SaveContext<Sidvall.Data.IDataRowProvider<global::Sidvall.LogManager.Data.ILogScopeItem>>> dataPortalContext)
        {
            global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItemCollection entityItems;
            System.Collections.Generic.Dictionary<string, object> ids;

            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));
            ids = new System.Collections.Generic.Dictionary<string, object>();
            if (storageManager.ObjectContext.Database.Connection.State == System.Data.ConnectionState.Closed)
                await storageManager.ObjectContext.Database.Connection.OpenAsync().ConfigureAwait(false);
            entityItems = await ProcessResourceObjectsAsync(storageManager, Sidvall.Data.DataRowState.Modified, ids, dataPortalContext.OperationContext.Item.DataItems, dataPortalContext.OperationContext.Settings, dataPortalContext.ObjectParameters).ConfigureAwait(false);
            foreach (var entityItem in entityItems)
            {
                 if (Sidvall.Data.DataRowContextManager.GetDataRowState(entityItem) == Sidvall.Data.DataRowState.Added)
                     storageManager.ObjectContext.LogScopeItem.Add((global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem)entityItem);
            }
            await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.SaveChangesAsync(storageManager.ObjectContext).ConfigureAwait(false);
            dataPortalContext.ResultValueList = entityItems;
            dataPortalContext.ResultValueIsNewObject = true;
        }

        #endregion
        #region UpdateItemAsync

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task UpdateItemAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<bool, Sidvall.Data.UpdateItemContext<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext)
        {
            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));
            if (storageManager.ObjectContext.Database.Connection.State == System.Data.ConnectionState.Closed)
                await storageManager.ObjectContext.Database.Connection.OpenAsync().ConfigureAwait(false);
            await ProcessDataRowItemAsync(storageManager, dataPortalContext.OperationContext.DataRowItem, dataPortalContext.OperationContext.Parameters, dataPortalContext.ObjectParameters).ConfigureAwait(false);
            await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.SaveChangesAsync(storageManager.ObjectContext).ConfigureAwait(false);
            var rowCount = await storageManager.ObjectContext.SaveChangesAsync().ConfigureAwait(false);
            dataPortalContext.ResultValueItem = rowCount > 0;
        }

        #endregion
        #region UpdateItemsAsync

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
        public static async Task UpdateItemsAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<int, Sidvall.Data.UpdateItemsContext<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataPortalContext)
        {
            if (dataPortalContext == null)
                throw new System.ArgumentNullException(nameof(dataPortalContext));
            if (storageManager.ObjectContext.Database.Connection.State == System.Data.ConnectionState.Closed)
                await storageManager.ObjectContext.Database.Connection.OpenAsync().ConfigureAwait(false);
            await ProcessDataRowItemsAsync(storageManager, dataPortalContext.OperationContext.DataRowItems, dataPortalContext.OperationContext.Parameters, dataPortalContext.ObjectParameters).ConfigureAwait(false);
            await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.SaveChangesAsync(storageManager.ObjectContext).ConfigureAwait(false);
            dataPortalContext.ResultValueItem = await storageManager.ObjectContext.SaveChangesAsync().ConfigureAwait(false);
        }

        #endregion
        #region ExecuteAsync

        static partial void OnExecute(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.Data.CommandCriteria, global::Sidvall.Data.CommandCriteria> dataPortalContext);
        public static async Task ExecuteAsync(global::Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, global::Sidvall.Business.DataPortalContext<global::Sidvall.Data.CommandCriteria, global::Sidvall.Data.CommandCriteria> dataPortalContext)
        {
            OnExecute(storageManager, dataPortalContext);
            await dataPortalContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion

        #endregion
        #region Private Members

        #region GetNextIdAsync

        internal static async Task<object> GetNextIdAsync(global::Sidvall.LogManager.Data.Fields.LogScopeItemField fieldId, System.Collections.Generic.Dictionary<string, object> ids, Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager)
        {
            object id;

            switch (fieldId)
            {
                case global::Sidvall.LogManager.Data.Fields.LogScopeItemField.LogScopeItemId:
                    if (!ids.TryGetValue("LogScopeItem.LogScopeItemId", out id))
                    {
                        id = (long)await (from o in storageManager.ObjectContext.LogScopeItem
                                                  orderby o.LogScopeItemId descending
                                                  select o.LogScopeItemId).FirstOrDefaultAsync().ConfigureAwait(false) + 1;
                    }
                    else
                        id = (long)id + 1;
                    ids["LogScopeItem.LogScopeItemId"] = id;
                    return id;
                default:
                    return null;
            }
        }

        #endregion
        #region PrepareFilter

        internal static System.Linq.IQueryable<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> PrepareFilter(System.Linq.IQueryable<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> query, global::Sidvall.Data.Filter<global::Sidvall.LogManager.Data.Fields.LogScopeItemField> filter)
        {
            return Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.PrepareFilter(query, filter, GetFieldName);
        }

        #endregion
        #region PrepareSort

        internal static System.Linq.IQueryable<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> PrepareSort(System.Linq.IQueryable<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> query, System.Collections.Generic.IEnumerable<global::Sidvall.Data.SortItem> sortItems)
        {
            return Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.PrepareSort(query, sortItems, GetFieldName);
        }

        #endregion
        #region ProcessIncludedEntities

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "includedEntity"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
        private static System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> ProcessIncludedEntities(System.Data.Entity.Infrastructure.DbQuery<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> query, System.Collections.Generic.IEnumerable<global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation> includedEntities)
        {
            if (includedEntities != null)
            {
                foreach (var includedEntity in includedEntities)
                {
                    switch (includedEntity)
                    {
                        case global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation.LogScope:
                            query = query.Include("LogScope");
                            break;
                        case global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation.LogScopeItemCategories:
                            query = query.Include("LogScopeItemCategory");
                            break;
                        case global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation.LogScopeLogScopeItems:
                            query = query.Include("LogScope.LogScopeItem");
                            break;
                        case global::Sidvall.LogManager.Data.Relations.LogScopeItemRelation.LogScopeItemCategoriesLogScopeItem:
                            query = query.Include("LogScopeItemCategory.LogScopeItem");
                            break;
                        default:
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
        
        #region ProcessDataRowItemsAsync

        internal static async Task ProcessDataRowItemsAsync(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.IEnumerable<Sidvall.Data.DataRowItem<global::Sidvall.LogManager.Data.Fields.LogScopeItemField>> dataRowItems, Sidvall.Data.ParameterCollection parameters, Sidvall.Data.ObjectParameterCollection objectParameters)
        {
            foreach (var dataRowItem in dataRowItems)
                await ProcessDataRowItemAsync(storageManager, dataRowItem, parameters, objectParameters).ConfigureAwait(false);
        }

        #endregion
        #region ProcessDataRowItemAsync

        static partial void OnBeforeProcessDataRowItemFieldValue(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, Sidvall.Data.DataRowItem<global::Sidvall.LogManager.Data.Fields.LogScopeItemField> dataRowItem, Sidvall.Data.ParameterCollection parameters, Sidvall.Data.ObjectParameterCollection objectParameters, global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem, Sidvall.Data.FieldValueItem fieldValueItem, global::Sidvall.Business.TaskContext taskContext);
        static partial void OnAfterProcessDataRowItem(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, Sidvall.Data.DataRowItem<global::Sidvall.LogManager.Data.Fields.LogScopeItemField> dataRowItem, Sidvall.Data.ParameterCollection parameters, Sidvall.Data.ObjectParameterCollection objectParameters, global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem, global::Sidvall.Business.TaskContext taskContext);
        internal static async Task ProcessDataRowItemAsync(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, Sidvall.Data.DataRowItem<global::Sidvall.LogManager.Data.Fields.LogScopeItemField> dataRowItem, Sidvall.Data.ParameterCollection parameters, Sidvall.Data.ObjectParameterCollection objectParameters)
        {
            global::Sidvall.Business.TaskContext taskContext;

            var key = global::Sidvall.LogManager.Data.Entity.SystemContext.Current.EntityFacade.LogScopeItemManager.ParseKey(dataRowItem.Key);
            var entityItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectAsync(from o in storageManager.ObjectContext.LogScopeItem
                                    where o.LogScopeItemId == key
                                    select o).ConfigureAwait(false);
            if (entityItem == null)
                return;
            foreach (var fieldValueItem in dataRowItem.FieldValueItems)
            {
                taskContext = new global::Sidvall.Business.TaskContext();
                OnBeforeProcessDataRowItemFieldValue(storageManager, dataRowItem, parameters, objectParameters, entityItem, fieldValueItem, taskContext);
                await taskContext.DoTaskAsync().ConfigureAwait(false);
                if (taskContext.Result == Sidvall.Business.DataPortalResult.None)
                {
                    global::Sidvall.LogManager.Data.Entity.SystemContext.Current.EntityFacade.LogScopeItemManager.LoadInstanceField(entityItem, fieldValueItem.FieldName,
                        fieldValueItem.GetFieldValue(), false, false, false);
                }
            }
            taskContext = new global::Sidvall.Business.TaskContext();
            OnAfterProcessDataRowItem(storageManager, dataRowItem, parameters, objectParameters, entityItem, taskContext);
            await taskContext.DoTaskAsync().ConfigureAwait(false);
        }

        #endregion
        #region ProcessResourceObjectsAsync

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal static async Task<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItemCollection> ProcessResourceObjectsAsync(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, Sidvall.Data.DataRowState rowState, System.Collections.Generic.Dictionary<string, object> ids, System.Collections.Generic.IEnumerable<global::Sidvall.LogManager.Data.ILogScopeItem> items, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters)
        {
            System.Collections.Generic.List<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> deletedItems;
            global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItemCollection entityItems;
            Sidvall.Data.IListContextProvider listContextProvider;
            global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem;

            if (items == null)
                return null;
            entityItems = new global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItemCollection();
            switch (rowState)
            {
                case Sidvall.Data.DataRowState.Added:
                    foreach (var item in items)
                    {
                        entityItem = await ProcessResourceObjectAsync(storageManager, ids, item, settings, objectParameters).ConfigureAwait(false);
                        if (entityItem != null)
                            entityItems.Add(entityItem);
                    }
                    return entityItems;
                default:
                    foreach (var item in items)
                    {
                        entityItem = await ProcessResourceObjectAsync(storageManager, ids, item, settings, objectParameters).ConfigureAwait(false);
                        if (entityItem != null)
                            entityItems.Add(entityItem);
                    }
                    listContextProvider = items as Sidvall.Data.IListContextProvider;
                    if (listContextProvider != null)
                    {
                        deletedItems = new System.Collections.Generic.List<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem>();
                        foreach (var deletedItemKey in listContextProvider.DeletedItemKeys)
                        {
                            var key = global::Sidvall.LogManager.Data.Entity.SystemContext.Current.EntityFacade.LogScopeItemManager.ParseKey(deletedItemKey);
                            entityItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectAsync(from o in storageManager.ObjectContext.LogScopeItem
                                                   where o.LogScopeItemId == key
                                                   select o).ConfigureAwait(false);
                            if (entityItem != null)
                                deletedItems.Add(entityItem);
                        }
                        if (deletedItems.Count > 0)
                        {
                            var taskContext = new global::Sidvall.Business.TaskContext();
                            OnRemove(storageManager, objectParameters, deletedItems, taskContext);
                            await taskContext.DoTaskAsync().ConfigureAwait(false);
                            if (taskContext.Result == Sidvall.Business.DataPortalResult.None)
                                storageManager.ObjectContext.LogScopeItem.RemoveRange(deletedItems);
                        }
                    }
                    return entityItems;
            }
        }

        #endregion
        #region ProcessResourceObjectAsync

        static partial void OnAfterProcessResourceObject(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.Dictionary<string, object> ids, global::Sidvall.LogManager.Data.ILogScopeItem item, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters, Sidvall.Data.DataRowState rowState, Sidvall.Business.PropertyEventData<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> eventData, global::Sidvall.Business.TaskContext taskContext);
        static partial void OnBeforeProcessResourceObject(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.Dictionary<string, object> ids, global::Sidvall.LogManager.Data.ILogScopeItem item, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters, Sidvall.Data.DataRowState rowState, Sidvall.Business.PropertyEventData<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> eventData, global::Sidvall.Business.TaskContext taskContext);
        static partial void OnBeforeAddResourceObject(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.Dictionary<string, object> ids, global::Sidvall.LogManager.Data.ILogScopeItem item, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters, Sidvall.Data.DataRowState rowState, Sidvall.Data.CopySettings copySettings, Sidvall.Business.PropertyEventData<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> eventData, global::Sidvall.Business.TaskContext taskContext);
        static partial void OnBeforeUpdateResourceObject(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.Dictionary<string, object> ids, global::Sidvall.LogManager.Data.ILogScopeItem item, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters, Sidvall.Data.DataRowState rowState, global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem, Sidvall.Data.CopySettings copySettings, global::Sidvall.Business.TaskContext taskContext);
        static partial void OnBeforeUnchangedResourceObject(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.Dictionary<string, object> ids, global::Sidvall.LogManager.Data.ILogScopeItem item, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters, Sidvall.Data.DataRowState rowState, global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem, Sidvall.Data.CopySettings copySettings, global::Sidvall.Business.TaskContext taskContext);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
        internal static async Task<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem> ProcessResourceObjectAsync(Sidvall.LogManager.Data.Entity.Model.StorageManager storageManager, System.Collections.Generic.Dictionary<string, object> ids, global::Sidvall.LogManager.Data.ILogScopeItem item, Sidvall.Data.SaveSettings settings, Sidvall.Data.ObjectParameterCollection objectParameters)
        {
            global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem entityItem;
            Sidvall.Data.CopySettings copySettings;
            Sidvall.Data.DataRowState rowState;
            Sidvall.Security.IPropertyAccessLevelProvider accessLevelProvider;
            
            if (item == null)
                return null;
            rowState = Sidvall.Data.SaveSettings.GetDataRowState(settings, item);
            var eventData = new Sidvall.Business.PropertyEventData<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem>(null);
            var taskContext = new global::Sidvall.Business.TaskContext();
            OnBeforeProcessResourceObject(storageManager, ids, item, settings, objectParameters, rowState, eventData, taskContext);
            await taskContext.DoTaskAsync().ConfigureAwait(false);
            entityItem = eventData.Value;
            if (taskContext.Result == Sidvall.Business.DataPortalResult.None)
            {
                switch (rowState)
                {
                    case Sidvall.Data.DataRowState.Added:
                        copySettings = Sidvall.Data.CopySettings.ItemCopy(Sidvall.Data.DataRowContextOption.StateAndKey, Sidvall.Data.DataRowState.Added);
                        eventData = new Sidvall.Business.PropertyEventData<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem>(null);
                        taskContext = new global::Sidvall.Business.TaskContext();
                        OnBeforeAddResourceObject(storageManager, ids, item, settings, objectParameters, rowState, copySettings, eventData, taskContext);
                        await taskContext.DoTaskAsync().ConfigureAwait(false);
                        if (taskContext.Result == Sidvall.Business.DataPortalResult.None)
                            entityItem = (global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem)global::Sidvall.LogManager.Data.Entity.SystemContext.Current.EntityFacade.LogScopeItemManager.Copy(item, copySettings);
                        else
                            entityItem = eventData.Value;
                        if (!Sidvall.Data.SaveSettings.GetKeepKey(settings))
                            entityItem.LogScopeItemId = (long)await GetNextIdAsync(global::Sidvall.LogManager.Data.Fields.LogScopeItemField.LogScopeItemId, ids, storageManager).ConfigureAwait(false);
                        accessLevelProvider = entityItem as Sidvall.Security.IPropertyAccessLevelProvider;
                        if (copySettings.IncludedProperty(accessLevelProvider, false, false, true, Sidvall.Data.DataType.Object, "LogScopeItem.LogScopeItemCategories", "LogScopeItemCategory"))
                            entityItem.LogScopeItemCategory = await LogScopeItemCategoryManager.ProcessResourceObjectsAsync(storageManager, Sidvall.Data.DataRowState.Added, ids, item.LogScopeItemCategories, settings, objectParameters).ConfigureAwait(false);
                        break;
                    case Sidvall.Data.DataRowState.Deleted:
                        entityItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectAsync(from o in storageManager.ObjectContext.LogScopeItem
                                                       where o.LogScopeItemId == item.LogScopeItemId
                                                       select o).ConfigureAwait(false);
                        if (entityItem != null)
                            storageManager.ObjectContext.LogScopeItem.Remove(entityItem);
                        return null;
                    case Sidvall.Data.DataRowState.Modified:
                        entityItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectAsync(from o in storageManager.ObjectContext.LogScopeItem
                                                       where o.LogScopeItemId == item.LogScopeItemId
                                                       select o).ConfigureAwait(false);
                        if (entityItem == null)
                            return null;
                        copySettings = Sidvall.Data.CopySettings.ItemCopy(Sidvall.Data.DataRowContextOption.StateAndKey, Sidvall.Data.DataRowState.Modified, Sidvall.Business.FieldCopyOptions.ManualNonPrimaryKeys);
                        taskContext = new global::Sidvall.Business.TaskContext();
                        OnBeforeUpdateResourceObject(storageManager, ids, item, settings, objectParameters, rowState, entityItem, copySettings, taskContext);
                        await taskContext.DoTaskAsync().ConfigureAwait(false);
                        if (taskContext.Result == Sidvall.Business.DataPortalResult.None)
                            global::Sidvall.LogManager.Data.Entity.SystemContext.Current.EntityFacade.LogScopeItemManager.Import(entityItem, item, copySettings);
                        else
                            entityItem.SetDataRowContext(item, Sidvall.Data.DataRowState.Modified);
                        accessLevelProvider = entityItem as Sidvall.Security.IPropertyAccessLevelProvider;
                        if (item.LogScopeItemCategories != null)
                        {
                            if (copySettings.IncludedProperty(accessLevelProvider, false, false, true, Sidvall.Data.DataType.Object, "LogScopeItem.LogScopeItemCategories", "LogScopeItemCategory"))
                                entityItem.LogScopeItemCategory = await LogScopeItemCategoryManager.ProcessResourceObjectsAsync(storageManager, Sidvall.Data.DataRowState.Modified, ids, item.LogScopeItemCategories, settings, objectParameters).ConfigureAwait(false);
                        }
                        break;
                    default:
                        if (!item.DataRowStateIsDirty)
                            return null;
                        entityItem = await Sidvall.LogManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectAsync(from o in storageManager.ObjectContext.LogScopeItem
                                                       where o.LogScopeItemId == item.LogScopeItemId
                                                       select o).ConfigureAwait(false);
                        if (entityItem == null)
                            return null;
                        entityItem.SetDataRowContext(item, Sidvall.Data.DataRowState.Unchanged);
                        copySettings = Sidvall.Data.CopySettings.ItemCopy(Sidvall.Data.DataRowContextOption.StateAndKey, Sidvall.Data.DataRowState.Modified, Sidvall.Business.FieldCopyOptions.ManualNonPrimaryKeys);
                        taskContext = new global::Sidvall.Business.TaskContext();
                        OnBeforeUnchangedResourceObject(storageManager, ids, item, settings, objectParameters, rowState, entityItem, copySettings, taskContext);
                        await taskContext.DoTaskAsync().ConfigureAwait(false);
                        accessLevelProvider = entityItem as Sidvall.Security.IPropertyAccessLevelProvider;
                        if (item.LogScopeItemCategories != null)
                        {
                            if (copySettings.IncludedProperty(accessLevelProvider, false, false, true, Sidvall.Data.DataType.Object, "LogScopeItem.LogScopeItemCategories", "LogScopeItemCategory"))
                                entityItem.LogScopeItemCategory = await LogScopeItemCategoryManager.ProcessResourceObjectsAsync(storageManager, Sidvall.Data.DataRowState.Modified, ids, item.LogScopeItemCategories, settings, objectParameters).ConfigureAwait(false);
                        }
                        break;
                }
                if (item.LogScope != null)
                {
                    if (copySettings.IncludedProperty(accessLevelProvider, false, false, true, Sidvall.Data.DataType.Object, "LogScopeItem.LogScope", "LogScope"))
                        entityItem.LogScope = await LogScopeManager.ProcessResourceObjectAsync(storageManager, ids, item.LogScope, settings, objectParameters).ConfigureAwait(false);
                }
            }
            eventData = new Sidvall.Business.PropertyEventData<global::Sidvall.LogManager.Data.Entity.Entities.LogScopeItem>(entityItem);
            taskContext = new global::Sidvall.Business.TaskContext();
            OnAfterProcessResourceObject(storageManager, ids, item, settings, objectParameters, rowState, eventData, taskContext);
            await taskContext.DoTaskAsync().ConfigureAwait(false);
            return eventData.Value;
        }

        #endregion
        #region GetFieldName

        private static string GetFieldName(Sidvall.Data.IFilterItem filterItem)
        {
            return GetFieldName(filterItem.FieldName);
        }
        private static string GetFieldName(Sidvall.Data.SortItem sortItem)
        {
            return GetFieldName(sortItem.FieldName);
        }
        private static string GetFieldName(string fieldName)
        {
            return fieldName;
        }

        #endregion

        #endregion
    }
}